package com.fast.orm.exec;

import cn.hutool.core.collection.CollUtil;
import com.fast.orm.cache.DataCache;
import com.fast.orm.config.FastAttributes;
import com.fast.orm.data.DataPackage;
import com.fast.orm.data.Expression;
import com.fast.orm.jdbc.JdbcImpl;

public class DeleteExecution {

    private final DataPackage dataPackage;

    public DeleteExecution(DataPackage dataPackage) {
        this.dataPackage = dataPackage;
    }

    /**
     * 通过主键删除
     * 如果设置逻辑删除,对逻辑删除的数据不进行操作
     *
     * @param primaryKeyValue 主键ID
     * @return 是否删除成功
     */
    public Integer deleteByPrimaryKey(Comparable<?> primaryKeyValue) {
        if (primaryKeyValue == null) {
            throw new RuntimeException(dataPackage.getTableMapper().getTableName() + ": 主键参数不能为空!!!");
        }
        dataPackage.addWhere(new DataPackage.ConditionData(dataPackage.getTableMapper().getPrimaryKeyField(),primaryKeyValue,DataPackage.Way.AND,Expression.Equal));
        return delete();
    }

    /**
     * 通过条件物理删除,如果启动了逻辑删除功能,本操作会自动将数据删除标记修改,不会进行物理删除,除非关闭逻辑删除保护
     * 条件参数至少存在1个,否则抛出异常
     *
     * @return 删除影响到的数据条数
     */
    public Integer delete() {
        if (CollUtil.isEmpty(dataPackage.getWhereList())) {
            throw new RuntimeException(dataPackage.getTableMapper().getTableName() + ": 删除操作必须设置条件!!!");
        }
        if (!dataPackage.getLogicDelete()) {
            Integer deleteNum = JdbcImpl.delete(dataPackage);

            return deleteNum;
        }
        try {
            dataPackage.getUpdateFieldMap()
                    .put(FastAttributes.deleteFieldName, new DataPackage.UpdateField(FastAttributes.deleteFieldName,
                            FastAttributes.defaultDeleteValue, DataPackage.UpdateField.UpdateType.EQUAL));
            return new UpdateExecution(dataPackage).update();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
